Playwright Locators. Handle Elements: Inputs, Buttons, Dropdown, Frames, Etc.

In this material, we will specifically focus on interacting with HTML input elements by writing Playwright locators, making use of its developed community and comprehensive documentation.

The Playwright tool is becoming more popular in the market. It supports multiple operating systems, various languages, and browsers.

The framework ensures reliable testing of modern web applications. Playwright locators also automates APIs. It supports the automation of browser-based mobile applications. Yet, you cannot use it to test native mobile digital solutions. Another advantage of the framework is its thriving community and extensive documentation. Let’s talk more in detail ⬇️

Playwright: Brief Overview of the Key Advantages

  • So, Playwright supports modern web apps, mobile web apps, and API testing. Regarding languages, it supports Javascript, Typescript, Java, Python, and .Net (C#).
  • The official website, playwright.dev, offers detailed documentation on working with the platform using various programming languages. The documents provide all necessary information, including framework installation, test generator execution, and a detailed description of all existing functions.
  • Regarding browser support, Playwright is compatible with most of them: Chromium, WebKit (Safari), and FireFox (headed/headless). With this framework, you can test applications for Windows, MacOS, Linux, or run tests in CI pipelines.
  • Playwright is entirely free and has open-source code. This means that no license purchase is required for its use – you can simply install it and start testing multiple elements.

Getting Started with Playwright Testing

Before you create tests, it’s crucial to define the frontend work. This task includes:

  1. Understanding the structure of the site interface to be tested multiple elements, specifically: → Inputs → Buttons → Dropdowns → Frames → Windows, etc.
  2. Anticipating potential future challenges and evaluating the possibility of preventing them. In other words, ask yourself, “What can I do to make the tests stable and effective?”
  3. Systematizing tests into logical groups and establishing the structure and steps of each individual test – that is, writing a basic test scenario.

Today, we will delve into Playwright locators in more detail, and you can find all the information about them in the relevant section of the documentation on the official site playwright.dev. Here, you’ll explore a list of built-in locators, including their usage. Consider the following DOM structure to understand their application and effectiveness in locating elements efficiently:

page.getByRole()
page.getByText()
page.getByLabel()
page.getByTitle() etc.

You’ll have direct access to each of them from this page accordingly.

Let’s move on to actions that can be performed with many HTML elements using Playwright locators.

Locating Elements in Playwright

If you need to act on any target element, the first step is identifying it. Such elements include input fields, video buttons, checkboxes, dropdowns, images, and links. These are different types of elements present on a web page. Consider the following DOM structure when identifying these elements.

To find the desired element, Playwright provides various ways or methods, and you must use locators for each of them. The search involves the element’s properties, which you can get from the DOM structure of the web page. The element must have a unique property or identifier. Playwright locators such as CSS selector and XPath selector can also be used to locate elements.

In CSS, there are four primary ways to select elements: by tag, class, ID, and attributes. You can combine these methods. Selectors can also be sensitive and whole string to case, allowing for precise and specific element targeting.

XPath – XML Path Language – can also effectively select elements on a web page. This query language lets you locate elements based on hierarchy, attributes, text, and provides many additional functions. Playwright locators offer a more straightforward and efficient way to select elements, especially for modern web applications.

In summary, XPath and CSS are powerful tools that allow precise selection of the necessary HTML elements for further interaction. Each has its own features, and both can be used for web testing automation. Although mostly AQA test engineers locate elements using CSS

What Methods Does Playwright Use to Locate and interact with Elements?

To interact any element on a web page in Playwright,  await page.locator(‘locating’).click() method is suitable. Here ‘locator’ can be specified properties of the element, CSS, or XPath.

There is another method:await .click(‘locating’)If the first method involves specifying the locator first and then performing the click action, the second method involves taking action on an element with a specific locator.

In most cases, the second approach is preferable. The first involves searching for an element by specifying the locator with the await page and then taking some action with the multiple elements. The second involves directly invoking the action.

Next, let’s discuss how Playwright can interact with HTML elements.

Actions on Elements Using Playwright Locators

After locating input elements, Playwright can perform specific actions on them. Let’s explore what actions the Playwright framework supports and how exactly it happens.

Input Value

To fill an input field in Playwright, the easiest method is to use locator.fill()

It focuses on a particular element and triggers an input event with entered text content. This is suitable for elements such as:

  • <input>
  • <textarea>
  • [contenteditable]

The generic usage of this locator looks like this:

await page.getByRole('textbox').fill('example value')

Specific use cases include:

// Text input
await page.getByRole('textbox').fill('Peter');

// Date input
await page.getByLabel('Bith date').fill('2020-02-02');

// Time input 
await page.getByLabel('Appointment time').fill('13:15');

//Local datetime input
await page.getByRole('Local time').fill('2020-03-02T05:15')
Setting, Unsetting Checkboxes and Selecting Radio Buttons

In the considered framework, the locator.setChecked() is used for this purpose. It is suitable for the following types of elements:

  • input[type=checkbox]
  • input[type=radio]
  • [role=checkbox]
To apply the locator, you need to write:
await page.getByRole('checkbox').setChecked(true)
Specific use cases depending on the particular multiple elements:
//Check the checkbox
await page.getByLabel('I agree to the terms above').check();

//Assert the checked state
expect(page.getByLabel('Subscribe to newsletter')).toBeChecked();

//Select the radio button
await page.getByLabel('XL').check();
Choose Parameter

Playwright lets you choose one or more parameters for the <select> element using locator.selectOption() Multiple selections are allowed, where the element is considered matching multiple option values. To perform these operations, first, locate the element within the DOM structure using appropriate selectors. For example:

<select multiple>
    <option value="red"></option>
    <option value="green"></option>
    <option value="blue"></option>
</select>
//Multiple selection for red, green and blue options
 element.selectOption(['red', 'green', 'blue']); 

//Multiple selected items
await page.getByLabel('Choose multiple colors').selectOption(['red', 'green', 'blue'])

Single selection is also possible, where there is an exact match of the element with one intended value or label.

Let’s consider this option with an example of selecting a color in an abstract web application:
//Single selection matching the value or label
element.selectOption('blue');

//Single selection matching the label
element.selectOption({label: 'Blue'});
//Single selection matching the value or label
await page.getByLabel('Choose a color').selectOption('blue');

//Single selection matching the label 
await page.getByLabel('Choose a color').selectOption({label: 'Blue'});
Mouse Click

It is an action that simulates a regular user clicking with the mouse. In Playwright, several click events are available:

//Single click event
await page.getByRole('button').click();

//Method double clicks
await page.getByText('Item').dblclick();

//Right-click
await page.getByText('Item').click({ button: 'right' });

//Shift + click
await page.getByText('Item').click({ modifiers: ['Shift'] });

//Hover over an element
await page.getByText('Item').hover();

//Click at a specific position, for example, in the top-left corner
await page.getByText('Item').click({ position: { x: 0, y: 0 } });
Let’s delve a little deeper into the technical aspects of carrying out such actions. These methods expect:
  • The focused element with the specified selector to be in the DOM and accessible.
  • The visibility of the element, i.e., the display property, should not be none, and the visibility should not be hidden;
  • The element to be static, for example, the end of a CSS transition between two states.
  • The system scrolls the element into view.
  • The DOM element receives pointer events at the action point.

If the matching element was accidentally detached and the check failed, the attempt is retried.

In some situations, a QA specialist may need to force a click, for example, if the click is intercepted by a non-target element. Ensuring the click targets the exact string or element is crucial to avoid unintended interactions or errors in test execution. In this case, use the locator:

await page.getByRole('button').click({ force: true });
For testing digital solutions in real conditions and checking any possible click variations, you should use locator.dispatchEvent():
await page.getByRole('button').dispatchEvent('click');
If you prefer not to use a locator, you can directly call the click method:
await page.click(‘id=login2’) 
// where instead of id=login2, you should specify the element's property.
Character Input

In addition to locator.fill(), provides another method for character input, which is used in situations where characters need to be entered one by one, mimicking the way a real user would do it. In this case, you should use locator:

await page.locator('#area').pressSequentially('Hello World!')

This method allows you to simulate the behavior of a real user down to the smallest details, including fine-grained keyboard events such as:

  • keydown
  • keyup
  • keypress etc.

The method also allows you to introduce delays between key presses to make the similarity to real user behavior as accurate as possible.

Keypress and Key Combinations: To perform key presses or execute the pressing of key combinations, locator.press() is used: await page.getByRole(‘textbox’).press(‘Backspace’);

In this case, the locator can take the name of the key to be pressed – in the example above, ‘Backspace’ can be replaced with one of these values:

Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, F1 – F12, Digit0 – Digit9, KeyA – KeyZ, etc.

You can create a single character or use key combinations, for example, to change the case or perform other modifications. Keys that can be pressed simultaneously include various combinations, which can be automated using Playwright locators for precise simulation and testing:

  • Shift;
  • Control;
  • Alt;
  • Meta.
Usage examples:
//<input id=name>
await page.locator('#name').press('Shift+A');

//<input id=name>
await page.locator('#name').press('Shift+ArrowLeft');
File Upload

To select and upload files, you can use the method locator.setInputFiles() Note that this method allows you to upload one or multiple files as the<input type=file> format.

Relative paths to files are resolved relative to the current working directory. An empty array clears the selected files.

// Select one file
await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));

// Select multiple files
await page.getByLabel('Upload files').setInputFiles([
    path.join(__dirname, 'file1.txt'),
    path.join(__dirname, 'file2.txt'),
]);

// Remove all the selected files
await page.getByLabel('Upload file').setInputFiles([]);

// Upload buffer from memory
await page.getByLabel('Upload file').setInputFiles({
    name: 'file.txt',
    mineType: 'text/plain',
    buffer: Buffer.from('this is test')
    
});

In case input elements are absent – if they are dynamically created – use page.on(‘filechooser’) or the waiting method:

//Start waiting for file chooser before clicking. Note no await.
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));
Focus on Element

In some web applications, there are focus events that assume only the appearance of the focused element. To focus on the exact element, allows the locator.focus() method:

await page.getByLabel('Password').focus();
Dragging an Element

Drag an element with locator.dragTo() This method involves the following actions:

  • Hover over the matching multiple elements.
  • Press the left mouse button.
  • Drag the element to the target element locator or position.
  • Release the left mouse button.
It will look like this:
await page.locator('#item-to-be-dragged').dragTo(page.locator('item-to-dop-at'));
For total control over the operation, manual dragging can be performed using other methods:
  • locator.hover();
  • mouse.down();
  • mouse.move();
  • mouse.up().
await page.locator('#item-to-be-dragged').hover();
await page.mouse.down();
await page.locator('#item-to-drop-at').hover();
await page.mouse.up();

Interacting with Web Page Dialogs: Playwright supports three types of dialogs

  • alert
  • confirm
  • prompt

By default, when you receive any notification in Playwright, the framework automatically handles and closes them. If there is a listener page.on('dialog'), it should handle the dialog; otherwise, any action will be halted. To avoid this, register a dialog handler before the action:Dialog.accept()or Dialog.Dismiss():

page.on('dialog', dialog => dialog.accept());
await page.getByRole('button').click();
Support for Multiple Tabs

Playwright supports working with multiple tabs out of the box, which can be useful in various scenarios for interacting with the content of each page:

// Create a page
const page = await context.newPage();

// Navigate explicity, similar to entering a URL in the browser
await page.locator('#sarch').fill('query');

// Navigate implicity by clicking a link
await page.locator('#submit').click();

Conclusion

Playwright is a powerful tool for automating web application testing. Among its numerous features, locating elements for subsequent actions is a crucial aspect. This material covered the basic ways of finding HTML elements using Playwright locators, considering the following DOM structure, utilizing attributes such as the title attribute to enhance element identification and interaction capabilities.

We hope this information proves useful to you. If you have any questions, feel free to reach out – the team is ready to share its experience in QA process automation.

Playwright extent report 📊
Simultaneously output manual and automated tests with the single test management tool
Follow us